//
//  SIMyDeviceViewController.m
//  CampingLight
//
//  Created by Piccolo on 2017/11/5.
//  Copyright © 2017年 SmartIT. All rights reserved.
//

#import "SIMyDeviceViewController.h"
#import "SIMyDeviceTableViewCell.h"
#import "SIMyDeviceOperationalView.h"
#import "SIOperationViewController.h"
#import "SIAutoReportInfo.h"
#import "SIMySceneViewController.h"
#import "SIDisplayLightInfo.h"
#import "SIChangeDeviceNameAlertView.h"
#import "SIHelpViewController.h"
#import "SIAboutViewController.h"

#import "RWDropdownMenu.h"
#import "TYAlertController+BlurEffects.h"
#import "UIView+TYAlertView.h"

static CGFloat const kBarBtnItemSpace = 20.f;
static CGFloat const kTableViewFooterHeight = 100.f;
static CGFloat const kTableViewHeight = 80.f;
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
static CGFloat const kConnectBleDelay = .5f;

///ImageView旋转状态枚举

typedef enum {
    
    RotateStateStop,
    
    RotateStateRunning,
    
}RotateState;

typedef NS_ENUM(NSUInteger, NSSIMyDeviceViewControllerAlertType){
    
    NSSIMyDeviceViewControllerAlertTypeSetting = 0x01,
    NSSIMyDeviceViewControllerAlertTypeScanning = 0x02,
};

//static NSString * const kDeviceName = @"YYD";
static NSString * const kDeviceName = @"Bedding Light";
//static NSString * const kDeviceName = @"Rayonics";
static NSString * const kDeviceName1 = @"B-Light ";
static NSInteger const kMaxDeviceSubNameLength = 6;

static RWDropdownMenuStyle const kMenuStyle = RWDropdownMenuStyleBlackGradient;


@interface SIMyDeviceViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, CBCentralManagerDelegate, SILightDelegate, SmartITOperationViewControllerDelegate, UIAlertViewDelegate, UIGestureRecognizerDelegate> {
    
    NSMutableArray <SICPSDKPeripheral *> *_lightsArray;
    NSMutableArray <SIDisplayLightInfo *> *_displayCampingLightsArray;
    SIMyDeviceOperationalView *_myDeviceOperationalView;
    SIOperationViewController *_smartITOperationViewController;
    SIMySceneViewController *_smartITMySceneViewController;
    SIAboutViewController *_aboutViewController;
    SIHelpViewController *_helpViewController;
    SIAutoReportInfo *_lightAutoReportInfo;
    SICPSDKPeripheral *_smartITPeripheral;
    BOOL _isScan;
    BOOL _timerStart;
    BOOL _didSetDeviceTime;
    DGActivityIndicatorView *_indicator;
    NSInteger _currentSelectIndexPathRow;
    UIBarButtonItem *_refreshBtnItem;
    UIBarButtonItem *_mySenceBtnItem;
    CBCentralManager *_bluetoothManager;
    NSTimer *_timer;

    SIChangeDeviceNameAlertView *_changeDeviceNameAlertView;
    TYAlertController *_alertController;
    RotateState _rotateState;
    ///旋转角度
    
    CGFloat _imageViewAngle;
    
    BOOL _didSetConnectedUI;
}

@property (nonatomic, strong) NSArray *menuItems;


@end

@implementation SIMyDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNaviBar];
    [self setupInitializationData];
    [self setupTableView];
    [self updateTableViewFooter];
    [self setupChangeDeviceNameView];
    [SICPSDKService initBlueToothManager];
    [SICPSDKService setDelegate:self];
    
    if (_smartITPeripheral && [SICPSDKService getCurrentBleState] != CBPeripheralStateConnected) {
        [_lightsArray removeAllObjects];
        [self updateDisplayLightArrayWithCurrentLightArray];
        [_myDevicesTableView reloadData];
        //        _connectStatusLabel.text = @"-- 已断开 --";
    } else if (_smartITPeripheral && [SIBleUtil bleIsConnected]) {
        //        _connectStatusLabel.text = @"-- 已连接 --";
    }
    
    [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [NSThread sleepForTimeInterval:.05f];
        if (![SICPSDKService getManagerScanning]) {
            [self startScan];
        }
    });
    [self registerNotification];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [SICPSDKService setDelegate:self];
}

- (void)registerNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBleAfterEnterForeground) name:@"search_ble_notification" object:nil];
}

- (void)setupInitializationData {
//    _lightsArray = [NSMutableArray arrayWithObjects:@"CampingLights1", @"CompingLights2", nil];
    
    NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @NO};
    _bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
    
    _lightsArray = [NSMutableArray array];
    [self updateDisplayLightArrayWithCurrentLightArray];
    [_myDevicesTableView reloadData];
    _indicator = [SIUtil newIndicatorWithTarget:self centerPoint:CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 3)];
    _didSetDeviceTime = NO;
}


- (void)setupNaviBar {
    self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_MY_DEVICE"];
    _refreshBtnItem = [SIUtil newBarItemWithImageName:@"ico-15.png" target:self action:@selector(refreshBtnOnClick:)];
    _mySenceBtnItem = [SIUtil newBarItemWithImageName:@"ico-01-64.png" target:self action:@selector(presentMenuFromNav:)];
    //调试
//    [SIUtil setBtn:(UIButton *)_mySenceBtnItem.customView enabled:NO];
    UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedItem.width = kBarBtnItemSpace;
    self.navigationItem.rightBarButtonItems = @[_mySenceBtnItem, fixedItem, _refreshBtnItem];

}

- (void)startTimer {
    _timer = [NSTimer new];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(distroyTimer:) userInfo:nil repeats:NO];
}

- (void)distroyTimer:(NSTimer *)timer {
//    [self updateTableViewFooter];
    _timer = nil;
}

- (void)setupTableView {
    _myDevicesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myDevicesTableView.backgroundColor = [UIColor clearColor];
    [self setupTableViewFooter];
    _myDevicesTableView.tableFooterView = _myDeviceOperationalView;
    _myDevicesTableView.tableFooterView.hidden = NO;
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1.0; //seconds
    lpgr.delegate = self;
    [_myDevicesTableView addGestureRecognizer:lpgr];
    
//    [_myDevicesTableView reloadData];
}

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:_myDevicesTableView];
    
    NSIndexPath *indexPath = [_myDevicesTableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        if ([SIBleUtil bleIsConnected]) {
            [self presentViewController:_alertController animated:YES completion:nil];
        }
        NSLog(@"long press on table view at row %ld", indexPath.row);
    } else {
        NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
    }
}

- (void)setupTableViewFooter {
    _myDeviceOperationalView = [[SIMyDeviceOperationalView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kTableViewFooterHeight)];
    [SIUtil setBtn:_myDeviceOperationalView.onOffBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(onOffBtnOnClick:)];
    [SIUtil setBtn:_myDeviceOperationalView.brightBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(brightBtnOnClick:)];
    [SIUtil setBtn:_myDeviceOperationalView.sosBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(sosBtnOnClick:)];
    _myDeviceOperationalView.onOffLabel.text = [SIUtil getSingleKeyStr:@"TEXT_ON_OFF"];
    _myDeviceOperationalView.lightLabel.text = [SIUtil getSingleKeyStr:@"TEXT_BRIGHTER"];
    _myDeviceOperationalView.sosLabel.text = [SIUtil getSingleKeyStr:@"TEXT_SOS"];
}

- (void)setupChangeDeviceNameView {
    
    _changeDeviceNameAlertView = [SIChangeDeviceNameAlertView createViewFromNib];
    _changeDeviceNameAlertView.titleLabel.text = [SIUtil getSingleKeyStr:@"TEXT_UPDATE_DEVICE_NAME"];
    _changeDeviceNameAlertView.nameTextField.returnKeyType = UIReturnKeyDone;
    _changeDeviceNameAlertView.nameTextField.delegate = self;
    _changeDeviceNameAlertView.layer.cornerRadius = 15.f;
    [SIUtil addBottomBorderToTextField:_changeDeviceNameAlertView.nameTextField leftViewText:kDeviceName1];
    [_changeDeviceNameAlertView.cancelBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_CANCEL"] forState:UIControlStateNormal];
    [_changeDeviceNameAlertView.saveBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_SAVE"] forState:UIControlStateNormal];
    
    [_changeDeviceNameAlertView.cancelBtn setTintColor:[UIColor redColor]];
    
    [SIUtil addBtn:_changeDeviceNameAlertView.cancelBtn target:self action:@selector(alertViewCancelBtnOnClick:)];
    [SIUtil addBtn:_changeDeviceNameAlertView.saveBtn target:self action:@selector(alertViewSaveBtnOnClick:)];
    _alertController = [TYAlertController alertControllerWithAlertView:_changeDeviceNameAlertView preferredStyle:TYAlertControllerStyleAlert];
}


- (void)updateTableViewFooter {
    
    BOOL isConnected = [SIBleUtil bleIsConnected];
    _myDeviceOperationalView.hidden = !isConnected;
    if (isConnected) {
        BOOL onOffBtnSelected = _lightAutoReportInfo.lightInfo.brightnessValue > 0 && _lightAutoReportInfo.lightInfo.mode != NSSILightModeOff;
        [SIUtil setBtn:_myDeviceOperationalView.onOffBtn selected:onOffBtnSelected];
        CGFloat brightnessValue = _lightAutoReportInfo.lightInfo.brightnessValue;
        if (brightnessValue > 0 && brightnessValue < 25) {
            brightnessValue = 25;
        }
        _myDeviceOperationalView.brightBtn.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:brightnessValue / 25 / 5.f];
        [SIUtil setBtn:_myDeviceOperationalView.sosBtn selected:_lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightSosStatus];
        [self setOperationalViewBtnEnabled:YES];
        
    } else {
        [SIUtil setBtn:_myDeviceOperationalView.onOffBtn selected:NO];
        [SIUtil setBtn:_myDeviceOperationalView.brightBtn selected:NO];
    }
    
//    _myDeviceOperationalView.onOffBtn setb
//    _myDeviceOperationalView.onOffBtn.alpha = ;
//    _myDeviceOperationalView.brightBtn.alpha = _lightAutoReportInfo.lightInfo.oneWattLight.smartITCampingLightBrightnessValue / 33 / 4.f;
}

- (void)setOperationalViewBtnEnabled:(BOOL)enabled {
    _myDeviceOperationalView.onOffBtn.enabled = enabled;
    BOOL lightIsOn = _lightAutoReportInfo.lightInfo.mode == NSSILightModeDimming && _lightAutoReportInfo.lightInfo.brightnessValue > 0;
    [SIUtil setBtn:_myDeviceOperationalView.brightBtn enabled:lightIsOn];
    _myDeviceOperationalView.sosBtn.enabled = enabled;
}

- (void)refreshBleAfterEnterForeground {
    
    if (_smartITPeripheral.peripheral.state != CBPeripheralStateConnected) {
        [self refreshBle];
    }
}

- (void)refreshBtnOnClick:(UIButton *)btn {
    
    if ([SIBleUtil bleIsConnected]) {
        UIAlertView *bleRefreshAlert = [[UIAlertView alloc] initWithTitle:[SIUtil getSingleKeyStr:@"TEXT_CONFIRM_DISCONNECT"] message:nil delegate:self cancelButtonTitle:[SIUtil getSingleKeyStr:@"TEXT_CANCEL"] otherButtonTitles:[SIUtil getSingleKeyStr:@"TEXT_DISCONNECT"], nil];
        bleRefreshAlert.delegate = self;
        bleRefreshAlert.tag = NSSIMyDeviceViewControllerAlertTypeScanning;
        [bleRefreshAlert show];
    } else {
        [self refreshBle];
    }

}

- (void)refreshBle {
    
    if (SICPSDKService.sharedManager.bluetoothIsOn) {
        if ([SICPSDKService getCurrentBleState] != CBPeripheralStateDisconnected) {
            [SICPSDKService disConnectBle];
        }
        NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @NO};
        _bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
        [_lightsArray removeAllObjects];
        [self updateDisplayLightArrayWithCurrentLightArray];
    } else {
        [self showBleSettingAlert];
    }
}

- (void)showBleSettingAlert {
    
    UIAlertView *bleSettingAlert = [[UIAlertView alloc] initWithTitle:[SIUtil getSingleKeyStr:@"TEXT_BLUETOOTH_PERMISSION_DENY"] message:[SIUtil getSingleKeyStr:@"TEXT_GO_TO_SET_BLUETOOTH_PERMISSION"] delegate:self cancelButtonTitle:[SIUtil getSingleKeyStr:@"TEXT_CONFIRM"] otherButtonTitles:nil, nil];
    bleSettingAlert.delegate = self;
    bleSettingAlert.tag = NSSIMyDeviceViewControllerAlertTypeSetting;
    [bleSettingAlert show];
}

//- (void)mySceneBtnOnClick:(UIButton *)btn {
//    if (!_smartITMySceneViewController) {
//        _smartITMySceneViewController = [[SIMySceneViewController alloc] initWithNibName:@"SIMySceneViewController" bundle:nil];
//    }
//    [self.navigationController pushViewController:_smartITMySceneViewController animated:YES];
//}

- (void)bottomControlBtnOnClick:(UIButton *)btn {
    if (!_smartITOperationViewController) {
        _smartITOperationViewController = [[SIOperationViewController alloc] initWithNibName:@"SIOperationViewController" bundle:nil];
        _smartITOperationViewController.delegate = self;
    }
    [self.navigationController pushViewController:_smartITOperationViewController animated:YES];
}

- (void)connectBtnOnClick:(UIButton *)btn {
    
    _didSetConnectedUI = NO;
    [SIUtil setIndicator:_indicator hidden:NO target:self aboveSubView:_myDevicesTableView];
    NSInteger indexPathRow = btn.tag;
    _currentSelectIndexPathRow = indexPathRow;
    if (_smartITPeripheral.peripheral.state != CBPeripheralStateConnected) {
        _smartITPeripheral = _displayCampingLightsArray[indexPathRow].SDKPeripheral;
        [SICPSDKService initSDK];
//        _connectStatusLabel.text = @"-- 连接中 --";
        NSLog(@"its on!");
    } else {
//        _connectStatusLabel.text = @"-- 断开中 --";
        [SICPSDKService disConnectBle];
        NSLog(@"its off!");
    }
    [SICPSDKService stopScan];
    [SIUtil setBtn:btn enabled:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kConnectBleDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SIUtil setBtn:btn enabled:YES];
    });
}

- (void)alertViewCancelBtnOnClick:(UIButton *)btn {
    
    [_changeDeviceNameAlertView hideView];
}

- (void)alertViewSaveBtnOnClick:(UIButton *)btn {
    
    NSString *deviceName = _changeDeviceNameAlertView.nameTextField.text;
    [SICPSDKService sendSettingDeviceName:deviceName];
    NSString *freshPeripheralName = [kDeviceName1 stringByAppendingString:deviceName];
    [SIUtil setHistoryPeripheralNameToUserDefault:freshPeripheralName];
    for (SIDisplayLightInfo *displayInfo in _displayCampingLightsArray) {
        if (displayInfo.SDKPeripheral.peripheral == _smartITPeripheral.peripheral) {
            displayInfo.peripheralName = freshPeripheralName;
            displayInfo.SDKPeripheral.identityName = freshPeripheralName;
            break;
        }
    }
    [_myDevicesTableView reloadData];
    NSLog(@"@261:device name : %@", deviceName);
    [_changeDeviceNameAlertView hideView];
    
}

- (NSInteger)brightnessDegreeFromValue:(NSInteger)value {
    return value / 25 % 5;
}

- (void)onOffBtnOnClick:(UIButton *)btn {
    
    [self setOperationalViewBtnEnabled:NO];
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];

    if (lightInfo.mode == NSSILightModeOff) {
        if (lightInfo.brightnessValue == 0) {
            [SIUtil setCampingLightInfo:lightInfo brightnessValue:25.f colorTempValue:lightInfo.colorTempValue];
        }
        [SIUtil setCampingLightInfo:lightInfo mode:NSSILightModeDimming];
    } else {
        [SIUtil setCampingLightInfo:lightInfo mode:NSSILightModeOff];
    }
    
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
//    [self startTimer];
    [self updateTableViewFooter];


    _lightAutoReportInfo.lightInfo = lightInfo;
}

- (void)brightBtnOnClick:(UIButton *)btn {
    
    [self setOperationalViewBtnEnabled:NO];
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    CGFloat currentBrightnessDegree = [self brightnessDegreeFromValue:lightInfo.brightnessValue];
//    [SIUtil setCampingLightInfo:lightInfo smartITOneWattCampingLightSettingMode:NSSILightModeOff smartITThreeWattCampingLightSettingMode:NSSILightModeOff];
    if (currentBrightnessDegree == 4) {
        currentBrightnessDegree = 1;
    } else {
        currentBrightnessDegree ++;
    }
//    [self startTimer];
    NSInteger brightnessValue = 25 * currentBrightnessDegree;
    [SIUtil setCampingLightInfo:lightInfo brightnessValue:brightnessValue colorTempValue:_lightAutoReportInfo.lightInfo.colorTempValue];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
    
    _lightAutoReportInfo.lightInfo = lightInfo;
    
    
//    if (!btn.tag) {
//        [btn setBackgroundColor:[UIColor lightGrayColor]];
//        btn.tag = 1;
//    } else {
//        [btn setBackgroundColor:[UIColor clearColor]];
//        btn.tag = 0;
//    }
}

- (void)sosBtnOnClick:(UIButton *)btn {
    [self setOperationalViewBtnEnabled:NO];
    SILightAddtionalInfo *lightAddtionalInfo = [_lightAutoReportInfo.lightInfo.lightAddtionalInfo copy];
    lightAddtionalInfo.lightSosStatus = lightAddtionalInfo.lightSosStatus ? 0 : 1;
    [SICPSDKService sendAdditionalCommandFromLightAddtionalInfo:lightAddtionalInfo];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _displayCampingLightsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"my_device_cell";
    SIMyDeviceTableViewCell *cell = (SIMyDeviceTableViewCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SIMyDeviceTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = _displayCampingLightsArray[indexPath.row].peripheralName;
        
//        UILongPressGestureRecognizer *nameLabelLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(nameLabelLongPressAction:)];
//        [cell.nameLabel addGestureRecognizer:nameLabelLongPress];
        
        cell.lineStatusLabel.text = _displayCampingLightsArray[indexPath.row].lightStatusType == NSSILightStatusTypeOnLine ? [SIUtil getSingleKeyStr:@"TEXT_ONLINE"] : [SIUtil getSingleKeyStr:@"TEXT_OFFLINE"];
        [cell.bleConnectBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_CONNECTED"] forState:UIControlStateNormal];
        [SIUtil setBtn:cell.bleConnectBtn enabled:_displayCampingLightsArray[indexPath.row].lightStatusType == NSSILightStatusTypeOnLine];
        [SIUtil addBtn:cell.bleConnectBtn target:self action:@selector(connectBtnOnClick:)];
        [SIUtil addBtn:cell.myDeviceBtn target:self action:@selector(bottomControlBtnOnClick:)];
        cell.bleConnectBtn.tag = indexPath.row;
        
        if ([SIUtil checkPlatformIsFiveType] || [SIUtil checkPlatformIsFourType]) {
            [SIUtil setRightView:cell.lineStatusLabel nextToView:cell.myDeviceBtn sameFrame:NO spacing:16.f];
            [SIUtil setRightView:cell.nameLabel nextToView:cell.myDeviceBtn sameFrame:NO spacing:16.f];
        }
        BOOL currentCellConnected = _displayCampingLightsArray[indexPath.row].SDKPeripheral.peripheral && _displayCampingLightsArray[indexPath.row].SDKPeripheral.peripheral.state == CBPeripheralStateConnected;
        [SIUtil setBtn:cell.myDeviceBtn enabled:currentCellConnected];
        if ([SIBleUtil bleIsConnected]) {
            
            [cell.bleConnectBtn setTitle:[SIUtil getSingleKeyStr:currentCellConnected ? @"TEXT_DISCONNECTED" : @"TEXT_CONNECTED"] forState:UIControlStateNormal];
        }
        else {
            [cell.bleConnectBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_CONNECTED"] forState:UIControlStateNormal];
//            [SIUtil setBtn:cell.bleConnectBtn enabled:YES];
        }
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kTableViewHeight;
}

#pragma mark - Bluetooth

- (void)stopScan {
    [_lightsArray removeAllObjects];
    [self updateDisplayLightArrayWithCurrentLightArray];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_myDevicesTableView reloadData];
    });
    [SICPSDKService stopScan];
    _isScan = NO;
    
}

- (void)startScan {
    
//    [self stopScan];
    
    UIBarButtonItem *refreshBtnItem = self.navigationItem.rightBarButtonItems[2];
    if ([SIUtil getDeviceVersion].integerValue >= 11) {
        _rotateState = RotateStateRunning;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _rotateState = RotateStateStop;
        });
        [self animate:refreshBtnItem];
    } else {
        [SIUtil setIndicator:_indicator hidden:NO target:self aboveSubView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:self.view];
        });
        
    }
    dispatch_async(dispatch_get_main_queue(), ^{
//        _connectStatusLabel.text = @"-- 搜索中 --";
    });
    if (!_lightsArray) {
        _lightsArray = [NSMutableArray new];
    }
    [_lightsArray removeAllObjects];
    if ([SIBleUtil bleIsConnected]) {
        SICPSDKPeripheral *smartItPeripheral = [SICPSDKService getCurrentBle];
        [_lightsArray addObject:smartItPeripheral];
    } else {
        //        [SICPSDKService disConnectBle];
    }
    [self updateDisplayLightArrayWithCurrentLightArray];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_myDevicesTableView reloadData];
    });
    
    [SICPSDKService startScan];
    
    if (![SICPSDKService sharedManager].delegate){
        
        [SICPSDKService setDelegate:self];
        
    }
    _isScan = YES;
}


- (BOOL)bleArrayContainsPeripheral:(SICPSDKPeripheral *)smartItPeripheral {
    for (SICPSDKPeripheral *per in _lightsArray) {
        if (per.peripheral == smartItPeripheral.peripheral) {
            return YES;
        };
    }
    return NO;
}

- (void)updateDisplayLightArrayWithCurrentLightArray {
    
    _displayCampingLightsArray = [NSMutableArray<SIDisplayLightInfo *> array];
    NSString *historyPeripheralName = [SIUtil userDefaultObjectForKey:SmartITHistoryLightNameKey];
    if ([SIUtil checkStringExist:historyPeripheralName]) {
        SIDisplayLightInfo *displayLightInfo = [SIDisplayLightInfo new];
        displayLightInfo.peripheralName = historyPeripheralName;
        NSInteger indexOfPeripheralName = [self lightArrayIndexOfPeripheralName:historyPeripheralName];
        if (indexOfPeripheralName != -1) {
            displayLightInfo.lightStatusType = NSSILightStatusTypeOnLine;
            displayLightInfo.SDKPeripheral = _lightsArray[indexOfPeripheralName];
        } else {
            displayLightInfo.lightStatusType = NSSILightStatusTypeOffLine;
            displayLightInfo.SDKPeripheral = nil;
        }
        [_displayCampingLightsArray addObject:displayLightInfo];
    }
    
    for (SICPSDKPeripheral *peripheralInfo in _lightsArray) {
        SIDisplayLightInfo *displayLightInfo = [SIDisplayLightInfo new];
        displayLightInfo.peripheralName = peripheralInfo.identityName;
        displayLightInfo.lightStatusType = NSSILightStatusTypeOnLine;
        displayLightInfo.SDKPeripheral = peripheralInfo;
        if (![displayLightInfo.peripheralName isEqualToString:historyPeripheralName]) {
            [_displayCampingLightsArray addObject:displayLightInfo];
        }
    }
    
}

- (NSInteger)lightArrayIndexOfPeripheralName:(NSString *)peripheralName {
    for (SICPSDKPeripheral *peripheralInfo in _lightsArray) {
        if ([peripheralInfo.identityName isEqualToString:peripheralName]) {
            return [_lightsArray indexOfObject:peripheralInfo];
        }
    }
    return -1;
}

- (void)setHistoryCampingLightInfoArrayFromLightNameArray:(NSArray *)lightNameArray {
    
    for (SICPSDKPeripheral *peripheral in _lightsArray) {
        SIDisplayLightInfo *lightInfo = [SIDisplayLightInfo new];
        
        lightInfo.peripheralName = peripheral.identityName;
        lightInfo.lightStatusType = NSSILightStatusTypeOnLine;
    }
}

#pragma mark - SetKeyControllerDelegate

- (void)scanedPeripheral:(SICPSDKPeripheral *)smartItPeripheral {
    
    
    if (![self bleArrayContainsPeripheral:smartItPeripheral]){
        BOOL filter = [SIUtil checkString:smartItPeripheral.peripheral.name containSubString:kDeviceName] ||
        [SIUtil checkString:smartItPeripheral.peripheral.name containSubString:kDeviceName1];
        if (filter) {
            [_lightsArray addObject:smartItPeripheral];
            [self updateDisplayLightArrayWithCurrentLightArray];
        }
    }
    CGRect tableViewFrame = _myDevicesTableView.frame;
    tableViewFrame.size.height = _lightsArray.count * 64.f;
    
    //    _bleTableView.backgroundColor = [UIColor redColor];
    //    _connectStatusLabel.backgroundColor = [UIColor greenColor];
    //    _bleTableView.frame = tableViewFrame;
//    CGRect labelFrame = _connectStatusLabel.frame;
//    labelFrame.origin.y = CGRectGetMaxY(tableViewFrame) + INNER_BOUNDS;
//    _connectStatusLabel.frame = labelFrame;
//    _connectStatusLabel.text = @"-- 搜索中 --";
//    CGRect indicatorFrame = _indicator.frame;
//    indicatorFrame.origin.y = CGRectGetMaxY(labelFrame) + INNER_BOUNDS;
//    _indicator.frame = indicatorFrame;
    [_myDevicesTableView reloadData];
    [_myDevicesTableView setNeedsLayout];
    [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:_myDevicesTableView];
    
}

- (void)requestInitSdkResultInfo:(SICPSDKResultInfo *)info{
    [SICPSDKService connectBlueTooth:_smartITPeripheral];
    
}

- (void)requestConnectResultInfo:(SICPSDKResultInfo *)info {
    
    SIMyDeviceTableViewCell *cell = (SIMyDeviceTableViewCell *)[_myDevicesTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentSelectIndexPathRow inSection:0]];
//    [SIUtil setBtn:(UIButton *)_mySenceBtnItem.customView enabled:info.feedBackState];
    if (info.feedBackState) {
//        _connectStatusLabel.text = @"-- 已连接 --";
        [cell.bleConnectBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_DISCONNECTED"] forState:UIControlStateNormal];
        [SIUtil setHistoryPeripheralNameToUserDefault:_smartITPeripheral.identityName];

    } else {
//        _connectStatusLabel.text = @"-- 连接失败 --";
        [cell.bleConnectBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_CONNECTED"] forState:UIControlStateNormal];
    }
//    [_myDevicesTableView reloadData];
//    [self updateTableViewFooter];
//    [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:_myDevicesTableView];
}

- (void)requestDisconnectResultInfo:(SICPSDKResultInfo *)info {
//    _connectStatusLabel.text = @"-- 已断开 --";
    _myDevicesTableView.tableFooterView.hidden = YES;
    _didSetDeviceTime = NO;
//    [SIUtil setBtn:(UIButton *)_mySenceBtnItem.customView enabled:NO];
    [_myDevicesTableView reloadData];
    [SICPSDKService stopScan];
    [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:_myDevicesTableView];
    [_smartITOperationViewController bleDisconnect];
    [_smartITMySceneViewController bleDisconnect];
}

- (void)currentRssi:(NSNumber *)rssi{
    
}

- (void)requestActiveReport:(SICPSDKResultInfo *)activeReportInfo {
    
    
    if ([SIUtil isExistDic:activeReportInfo.detailDic key:@"auto_basic_report_data"]) {
        _lightAutoReportInfo = [[SIAutoReportInfo alloc] initWithSmartITCampingLightAutoReportInfoData:activeReportInfo.detailDic[@"auto_basic_report_data"]];
        if (_lightAutoReportInfo.lightVoltage == 4) {
//        if (YES) {
            [SVProgressHUD showErrorWithStatus:[SIUtil getSingleKeyStr:@"TEXT_LOW_BATTERY"]];
            [SICPSDKService disConnectBle];
            [SICPSDKService stopScan];
            return;
        }
    }
    
    if (!_didSetConnectedUI) {
//        [self updateTableViewFooter];
//        _displayCampingLightsArray
        NSMutableArray<SIDisplayLightInfo *> *tempLightInfoArray = [NSMutableArray<SIDisplayLightInfo *> new];
       
        for (SIDisplayLightInfo *lightInfo in _displayCampingLightsArray) {
            NSLog(@"@676name:%@-state%ld", lightInfo.peripheralName, lightInfo.SDKPeripheral.peripheral.state);
            if (lightInfo.SDKPeripheral.peripheral.state == CBPeripheralStateConnected) {
                [tempLightInfoArray addObject:lightInfo];
            }
//            break;
        }
        _displayCampingLightsArray = tempLightInfoArray;
        [_myDevicesTableView reloadData];
        [SIUtil setIndicator:_indicator hidden:YES target:self aboveSubView:_myDevicesTableView];
        _didSetConnectedUI = YES;
    }
    [self updateTableViewFooter];
    if (!_didSetDeviceTime) {
        [SICPSDKService sendSettingDeviceTime];
        _didSetDeviceTime = YES;
    }
    [_smartITOperationViewController updateAutoReport:activeReportInfo];
    [_smartITMySceneViewController updateAutoReport:activeReportInfo];
}

- (void)requestStopScanBle {
//    _connectStatusLabel.text = @"-- 请刷新 --";
    _rotateState = RotateStateStop;
    if ([SICPSDKService getCurrentBleState] != CBPeripheralStateConnected) {
        
    }
}


#pragma mark - SmartITOperationViewControllerDelegate

- (void)didSendRequest {
//    [self startTimer];
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(_bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off.";
            SICPSDKService.sharedManager.bluetoothIsOn = NO;
            break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use.";
            SICPSDKService.sharedManager.bluetoothIsOn = YES;
            [self startScan];
            break;
        default: stateString = @"State unknown, update imminent.";
            break;
    }
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bluetooth state"
    //                                                    message:stateString
    //                                                   delegate:nil
    //                                          cancelButtonTitle:@"ok" otherButtonTitles: nil];
    //    [alert show];
}


#pragma mark - NavigationBar

- (void)presentMenuFromNav:(id)sender
{
    RWDropdownMenuCellAlignment alignment = RWDropdownMenuCellAlignmentRight;
    [RWDropdownMenu presentFromViewController:self withItems:self.menuItems align:alignment style:kMenuStyle navBarImage:[UIImage imageNamed:@"ico-01-64.png"] completion:nil];
}

- (NSArray *)menuItems
{
    if (_smartITPeripheral.peripheral.state != CBPeripheralStateConnected)
    {
        
        _menuItems =
        @[
          [RWDropdownMenuItem itemWithText:[SIUtil getSingleKeyStr:@"TEXT_HELP"] image:[UIImage imageNamed:@"help.png"] action:^{
              [self helpBtnOnClick];
          }],
          [RWDropdownMenuItem itemWithText:[SIUtil getSingleKeyStr:@"TEXT_ABOUT"] image:[UIImage imageNamed:@"about.png"] action:^{
              [self aboutBtnOnClick];
          }],
          ];
    } else {
        _menuItems =
        @[
          [RWDropdownMenuItem itemWithText:[SIUtil getSingleKeyStr:@"TEXT_SCENE"] image:[UIImage imageNamed:@"my_scene.png"] action:^{
              [self senceBtnOnClick];
          }],
          [RWDropdownMenuItem itemWithText:[SIUtil getSingleKeyStr:@"TEXT_HELP"] image:[UIImage imageNamed:@"help.png"] action:^{
              [self helpBtnOnClick];
          }],
          [RWDropdownMenuItem itemWithText:[SIUtil getSingleKeyStr:@"TEXT_ABOUT"] image:[UIImage imageNamed:@"about.png"] action:^{
              [self aboutBtnOnClick];
          }],
          ];
    }
    return _menuItems;
}

- (void)senceBtnOnClick {
    NSLog(@"@505");
//    if (!_smartITMySceneViewController) {
//        _smartITMySceneViewController = [[SIMySceneViewController alloc] initWithNibName:@"SIMySceneViewController" bundle:nil];
//    }
    _smartITMySceneViewController = [[SIMySceneViewController alloc] initWithNibName:@"SIMySceneViewController" bundle:nil];
    [self.navigationController pushViewController:_smartITMySceneViewController animated:YES];
}

- (void)helpBtnOnClick {
    NSLog(@"@509");
    if (!_helpViewController) {
        _helpViewController = [[SIHelpViewController alloc] initWithNibName:@"SIHelpViewController" bundle:nil];
    }
    [self.navigationController pushViewController:_helpViewController animated:YES];
}

- (void)aboutBtnOnClick {
    NSLog(@"@5013");
    if (!_aboutViewController) {
        _aboutViewController = [[SIAboutViewController alloc] initWithNibName:@"SIAboutViewController" bundle:nil];
    }
    [self.navigationController pushViewController:_aboutViewController animated:YES];
}

#pragma mark - UITextFiledDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Prevent crashing undo bug – see note below.
    if (textField == _changeDeviceNameAlertView.nameTextField) {
        NSUInteger lengthOfString = string.length;  //lengthOfString的值始终为1
        for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
            
            unichar character = [string characterAtIndex:loopIndex]; //将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
            
            // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
            
            if (character < 48) return NO; // 48 unichar for 0
            
            if (character > 57 && character < 65) return NO; //
            
            if (character > 90 && character < 97) return NO;
            
            if (character > 122) return NO;
            
            
        }
        if(range.length + range.location > textField.text.length)
        {
            return NO;
        }
        
        NSUInteger newLength = textField.text.length + lengthOfString - range.length;
        return newLength <= kMaxDeviceSubNameLength;
    }
    return YES;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    NSLog(@" button index=%d is clicked.....", buttonIndex);
    
    switch (alertView.tag) {
        case NSSIMyDeviceViewControllerAlertTypeSetting:
            switch (buttonIndex) {
                case 0:
                    break;
                    
                default:
                    break;
            }
            break;
        case NSSIMyDeviceViewControllerAlertTypeScanning:
            switch (buttonIndex) {
                case 0:
                    break;
                case 1:
                    [self refreshBle];
                    break;
                    
                default:
                    break;
            }
            break;
            
        default:
            break;
    }
    
}

#pragma mark - rotate

- (void)animate:(UIBarButtonItem *)buttonItem {
    
    //改变ImageView旋转状态
    if (_rotateState==RotateStateStop) {
//        _rotateState=RotateStateRunning;
//        [self rotateAnimate:buttonItem];
    }else{
//        _rotateState=RotateStateStop;
        [self rotateAnimate:buttonItem];
    }
}

#pragma mark 旋转动画

- (void)rotateAnimate:(UIBarButtonItem *)buttonItem {
    
    _imageViewAngle+=45;
    
    //0.5秒旋转50度
    
    if ([SIUtil isAtMainThread]) {
        [UIView animateWithDuration:.5f delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
            
            UIView *view = [buttonItem valueForKey:@"view"];
            view.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(_imageViewAngle));
            
        } completion:^(BOOL finished) {
            if (_rotateState==RotateStateRunning) {
                [self rotateAnimate:buttonItem];
            }
        }];
    }
}


@end
